'use strict';
// 验签盐
const JINR_REQUEST_SECRET = '4af1dd714f7397a108b503e93b6f59fe'
const md5 = require('md5')
const Controller = require('egg').Controller

class pushEvent extends Controller {
  async pushMessage() {
    const {
      ctx,
      service
    } = this
    try {
      const parts = ctx.multipart({
        autoFields: true
      })
      await parts()
      const {
        data,
        sign
      } = parts.field

      // 字段校验
      if (!ctx.helper.isNullFiled({
          data,
          sign
        })) {
        ctx.body = 'fail'
        return false
      }
      //校验签名
      let str = data + JINR_REQUEST_SECRET
      if (!ctx.helper.checkSign(str, sign)) {
        ctx.body = 'fail'
        ctx.logger.info(`签名sign不正确`)
        return false
      }
      let tmp = JSON.parse(data)
      ctx.body = {
        msg: 'success',
        data: tmp
      }
      console.log(tmp.code === 'buy', '-----jjjjjj----')
      // 判断时间类型
      if (tmp.code === 'buy') { //购买
        // 通过活动投资
        if (tmp.event_ref_id.toString().indexOf('#') !== -1) {
          let splitStr = tmp.event_ref_id.toString().split('#')
          await service.pushEvent.buy(tmp, splitStr)
        }

        let isInvited = await service.common.findOne(`
          SELECT activity_id, combination_id, invite_uid
          FROM hd_invite_relation
          WHERE uid = ${tmp.userid}
          `)

        if (isInvited) { // 活动注册，参与活动
          let {
            activity_id,
            combination_id,
            invite_uid
          } = isInvited;
          let splitStr = [combination_id, activity_id, '', invite_uid];
          await service.pushEvent.buy(tmp, splitStr,true)
        }

        ctx.body = 'ok'
      } else if (tmp.code === 'register') {
        let {
          userid,
          mobile,
          platform,
          event_ref_id,
          event_id,
          regTime
        } = $tmp;
        let params = {
          userid: userid,
          mobile: `'${mobile}'`,
          platform: platform,
          event_ref_id: event_ref_id,
          reg_time: `'${regTime}'`,
          push_event_id: event_id

        }
        await service.common.insertOne('hd_user', params)
      } else {
        ctx.body = 'ok'
      }

    } catch (error) {
      ctx.body = 'fail'
      console.log(error, `推送报错`)
    }
  }
}
module.exports = pushEvent